package com.dlc.longweisheng.chongdianxian.pub.base;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.aplus.kira.kiralibrary.tools.permission.PermissionUtil;
import com.dlc.longweisheng.chongdianxian.App;
import com.dlc.longweisheng.chongdianxian.pub.mInterface.ActivityResultCallback;
import com.hoho.android.usbserial.util.LogPlus;
import com.licheedev.adaptscreen.AdaptScreenEx;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.dlc.commonlibrary.utils.ToastUtil;


/**
 * Author:KiraWu
 */
public abstract class BaseActivity extends AppCompatActivity {
    private Unbinder unbinder;
    private ProgressDialog progressDialog;
    private int requestCode;

    @CallSuper
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeSetContentView(savedInstanceState);
        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
        }

        unbinder = ButterKnife.bind(this);
    }


    public abstract int getLayoutId();

    public void beforeSetContentView(Bundle savedInstanceState) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(true);
    }

    @Override
    public Resources getResources() {
        return toModifyResource(super.getResources());
    }

    /**
     * 修改Resources
     *
     * @param originalResources 没动过手脚的Resources
     * @return
     */
    protected Resources toModifyResource(Resources originalResources) {
        // 建议先在Application里面初始化  AdaptScreenEx.init(context);
        return AdaptScreenEx.adaptShorter(originalResources, 1080); // 假如设计图短边为1080像素
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        PermissionUtil.getInstance(getApplicationContext()).onDestroy();
    }

    public void startActivity(Class<?> cls) {
        startActivity(new Intent(getApplicationContext(), cls));
    }

    public void startActivity(Class<?> cls, int requestCode, ActivityResultCallback resultCallback) {
        this.requestCode = requestCode;
        this.resultCallback = resultCallback;
        startActivityForResult(new Intent(getApplicationContext(), cls), requestCode);
    }

    public void startActivity(Intent intent, int requestCode, ActivityResultCallback resultCallback) {
        this.requestCode = requestCode;
        this.resultCallback = resultCallback;
        startActivityForResult(intent, requestCode);
    }

    private ActivityResultCallback resultCallback;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance(getApplicationContext()).onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == this.requestCode && resultCallback != null) {
            resultCallback.onResult(data);
        }
    }

    public void showProgressDialog(String message, long timeout, Runnable onProgressDialogTimeoutRunnable) {
        progressDialog.setMessage(message);
        if (!isDestroyed()) {
            progressDialog.show();
            if (timeout != 0) {
                this.onProgressDialogTimeoutRunnable = onProgressDialogTimeoutRunnable;
                App.getInstance().getMainHandler().removeCallbacks(progressDialogTimeoutRunnable);
                App.getInstance().getMainHandler().postDelayed(progressDialogTimeoutRunnable, timeout);
            }
        }
    }

    private final Runnable progressDialogTimeoutRunnable = new Runnable() {
        @Override
        public void run() {
            if (onProgressDialogTimeoutRunnable != null) onProgressDialogTimeoutRunnable.run();
            dismissProgressDialog();
        }
    };
    private Runnable onProgressDialogTimeoutRunnable;

    public void showProgressDialog(String message) {
        showProgressDialog(message, 0, null);
    }

    public void showProgressDialog() {
        showProgressDialog("加载中...");
    }

    public void dismissProgressDialog() {
        progressDialog.dismiss();
        App.getInstance().getMainHandler().removeCallbacks(progressDialogTimeoutRunnable);
        onProgressDialogTimeoutRunnable = null;
    }

    public float getDimension(int id) {
        return getResources().getDimension(id);
    }


    public void showOne(String toast) {
        ToastUtil.showOne(getApplicationContext(), toast);
    }

    public String getEditString(EditText editText) {
        return editText.getText().toString().trim();
    }

    public String getTextString(TextView textView) {
        return textView.getText().toString().trim();
    }

    public void spm(String log) {
        LogPlus.e("showPrintMsg", log);
    }

    public void showDatePickDialog(final TextView textView) {
        final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // 获取一个日历对象
        final Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);

        // 当点击DatePickerDialog控件的设置按钮时，调用该方法
        DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                // 修改日历控件的年，月，日
                // 这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
                dateAndTime.set(Calendar.YEAR, year);
                dateAndTime.set(Calendar.MONTH, monthOfYear);
                dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                textView.setText(formatter.format(dateAndTime.getTime()));
            }
        };
        // 生成一个DatePickerDialog对象，并显示。显示的DatePickerDialog控件可以选择年月日，并设置
        new DatePickerDialog(this, d, dateAndTime.get(Calendar.YEAR),
                dateAndTime.get(Calendar.MONTH),
                dateAndTime.get(Calendar.DAY_OF_MONTH)).show();

    }
}
